package com.ad2campaign.engine.core.tasklet;

import org.apache.log4j.Logger;
import org.apache.log4j.lf5.util.StreamUtils;
import org.springframework.batch.core.StepContribution;
import org.springframework.batch.core.scope.context.ChunkContext;
import org.springframework.batch.core.step.tasklet.Tasklet;
import org.springframework.batch.repeat.RepeatStatus;
import org.springframework.jdbc.core.JdbcTemplate;

import com.ad2campaign.engine.core.TaskStatus;
import com.ad2campaign.engine.db.dao.PushNotificationMasterDao;
import com.ad2campaign.engine.db.model.Keystore;
import com.ad2campaign.engine.utils.KeystoreHolder;

public class PopulatePushDataTasklet implements Tasklet {
	private static final Logger LOGGER = Logger.getLogger(PopulatePushDataTasklet.class);
	private JdbcTemplate jdbcTemplate;
 	private String populateQuery;
 	private String keyStoreId ;
 	private Integer cId;
 	private Integer pushNotficationMasterId;
  
 




	private PushNotificationMasterDao pushNotificationMasterDao;



	@Override
	public RepeatStatus execute(StepContribution arg0, ChunkContext chunkContext)throws Exception 
	{
 		
		String sql = populateQuery.trim();
		LOGGER.info("Executing query: "+sql);
		int rowsAffected = jdbcTemplate.update(sql);
 		rowsAffected = 		pushNotificationMasterDao.updateMessageStatusAndProcucedById(pushNotficationMasterId,  TaskStatus.RUNNING.getStatusValue(),rowsAffected);
		KeystoreHolder keystoreHolder = new KeystoreHolder();
		Keystore keystore = pushNotificationMasterDao.findKeyStoreByCid(cId) ;
		keystoreHolder.setData(StreamUtils.getBytes(keystore.getKeystore().getBinaryStream()));
		keystoreHolder.setPwd(keystore.getPassword());
		keystoreHolder.setAndroidApiKey(keystore.getAndroid_api_key());
 		chunkContext.getStepContext().getStepExecution().getJobExecution().getExecutionContext().put("keystoreHolder",keystoreHolder );
		
 		return RepeatStatus.FINISHED;
	}

 
 
	public JdbcTemplate getJdbcTemplate() {
		return jdbcTemplate;
	}

	public void setJdbcTemplate(JdbcTemplate jdbcTemplate) {
		this.jdbcTemplate = jdbcTemplate;
	}

	public String getKeyStoreId() {
		return keyStoreId;
	}


	public void setKeyStoreId(String keyStoreId) {
		this.keyStoreId = keyStoreId;
	}
	

	public PushNotificationMasterDao getPushNotificationMasterDao()
	{
		return pushNotificationMasterDao;
	}


	public void setPushNotificationMasterDao(PushNotificationMasterDao pushNotificationMasterDao) 
	{
		this.pushNotificationMasterDao = pushNotificationMasterDao;
	}


	public Integer getcId() {
		return cId;
	}


	public void setcId(Integer cId) {
		this.cId = cId;
	}
	public Integer getPushNotficationMasterId() {
		return pushNotficationMasterId;
	}


	public void setPushNotficationMasterId(Integer pushNotficationMasterId) {
		this.pushNotficationMasterId = pushNotficationMasterId;
	}
  	public String getPopulateQuery() {
		return populateQuery;
	}


	public void setPopulateQuery(String populateQuery) {
		this.populateQuery = populateQuery;
	}

}
